class Solution {
    public int minFallingPathSum(int[][] matrix) {
        // 创建dp表、初始化、填表、返回值

        int m = matrix.length, n = matrix[0].length;
        int[][] dp = new int[m][n];

        for (int i = 0; i < n; i++) {
            dp[0][i] = matrix[0][i];
        }

        for (int i = 1; i < m; i++) {
            for (int j = 0; j < n; j++) {
                // 求出三者的值
                int x = Integer.MAX_VALUE, y = Integer.MAX_VALUE, z = Integer.MAX_VALUE;
                if (j-1 >= 0) {
                    x = dp[i-1][j-1];
                }
                y = dp[i-1][j];
                if (j+1 < n) {
                    z = dp[i-1][j+1];
                }
                dp[i][j] = Math.min(Math.min(x, y), z) + matrix[i][j];
            }
        }

        int ret = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            if (dp[m-1][i] < ret) {
                ret = dp[m-1][i];
            }
        }

        return ret;
    }
}